package com.smz.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smz.dao.SCompanyDAO;
import com.smz.dao.SupplierDAO;
import com.smz.dao.TRelationDAO;
import com.smz.entity.SCompany;
import com.smz.entity.Supplier;
import com.smz.entity.TRelation;
import com.smz.service.SCompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SCompanyServiceImpl extends ServiceImpl<SCompanyDAO,SCompany> implements SCompanyService {
    @Autowired
    SCompanyDAO sCompanyDAO;
    @Autowired
    SupplierDAO supplierDAO;
    @Autowired
    TRelationDAO tRelationDAO;
    @Override
    public SCompany findComByCompanyName(String companyName) {
        return sCompanyDAO.selectComByCompanyName(companyName);
    }


    @Override
    public List<SCompany> findAllSCompany() {
        return sCompanyDAO.selectAllSCompany();
    }

    @Transactional
    @Override
    public String addCompany(SCompany company) {
        company.setCompanyStatus("未注册");
        sCompanyDAO.insertCompany(company);//添加公司
        Supplier supplier = new Supplier(0,company.getCompanyName(),(company.getCompanyProvince()+company.getCompanyCity()+company.getCompanyArea()),company.getFixedTel(),company.getCompanyEmail(),company.getBusinessScope(),company.getLegal());
        supplierDAO.insertSupplier(supplier);//添加供销商
        Supplier supplier1 = supplierDAO.selectSuppByName(supplier.getName());
        SCompany sCompany = sCompanyDAO.selectComByCompanyName(company.getCompanyName());
        sCompany.setCompanyId(sCompany.getId());
        sCompanyDAO.updateById(sCompany);
        tRelationDAO.insert(new TRelation(0,supplier.getBusiness(),company.getCompanyIntroduction(),sCompany.getId(),supplier1.getId()));
        return "ok";
    }

    @Override
    public IPage<SCompany> findLike(int current, int size, String companyProvince, String companyCity, String companyArea, String companyName) {
        return sCompanyDAO.selectLike(new Page(current,size),companyProvince,companyCity,companyArea,"%"+companyName+"%");
    }

    @Override
    public IPage<SCompany> findCompany(int current, int size) {
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return sCompanyDAO.selectAllCompany(new Page(current,size),principal.getUsername());
    }

}
